package com.lct.todo.daoimpl;

import com.lct.todo.bean.TaskBean;
import com.lct.todo.dao.ITaskDao;
import com.lct.todo.daofactory.DaoFactory;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class TaskDaoImpl implements ITaskDao {
    /**
     * 插入
     *
     * @param taskBean TaskBean
     * @return 插入结果
     */
    @Override
    public int insert(TaskBean taskBean) {
        String sql = "insert into task(task_name, task_create_time) values(?, ?)";
        String[] paras = {taskBean.getTaskName(), taskBean.getTaskCreateTime()};
        return DaoFactory.exeUp(sql, paras);
    }

    /**
     * 根据id更新
     *
     * @param taskId 任务id
     * @return 更新结果
     */
    @Override
    public int updateTaskState(String taskId) {
        String sql = "update task set task_state = ? where task_id = ?";
        String[] paras = {"1", taskId};
        return DaoFactory.exeUp(sql, paras);
    }

    /**
     * 根据id删除
     *
     * @param taskId taskId
     * @return 删除结果
     */
    @Override
    public int delete(String taskId) {
        String sql = "delete from task where task_id = ?";
        String[] paras = {taskId};
        return DaoFactory.exeUp(sql, paras);
    }

    /**
     * 查询所有
     *
     * @return 任务数据集合
     */
    @Override
    public List<TaskBean> findAll() {
        String sql = "select * from task";
        ResultSet rs = DaoFactory.exeQu(sql, null);
        List<TaskBean> list = null;
        try {
            list = new ArrayList<>();
            TaskBean taskBean;
            while (rs.next()) {
                taskBean = new TaskBean(
                        rs.getInt(1),
                        rs.getString(2),
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(rs.getTimestamp(3)),
                        rs.getInt(4));
                list.add(taskBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DaoFactory.closeAll();
        return list;
    }
}
